package com.sw.rpc.server;

import com.sw.rpc.handler.UserServerHandler;
import com.sw.rpc.service.JSONSerializer;
import com.sw.rpc.service.RpcDecoder;
import com.sw.rpc.service.RpcRequest;
import com.sw.rpc.service.zk.RpcResponse;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @author sw
 * @project zdy-rpc
 * @description 提供者服务启动
 * @date 2020/5/15 13:17
 */
public class ProviderServer {
    /**
     * 初始化服务
     * @param hostName
     * @param port
     */
    public static void startServer(String hostName,int port) throws InterruptedException {
        //请求资源调度
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(eventLoopGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel sc) throws Exception {
                        ChannelPipeline p = sc.pipeline();
                      /*  p.addLast(new StringDecoder());*/
                     /*   p.addLast(new RpcDecoder(RpcResponse.class,new JSONSerializer()));
                        p.addLast( new RpcDecoder(RpcRequest.class, new JSONSerializer()));*/
                        p.addLast(new StringDecoder());
                        p.addLast(new StringEncoder());
                        p.addLast(new UserServerHandler());
                    }
                });
        serverBootstrap.bind(hostName,port).sync();

    }

}
